package com.accelstack.cmp.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * CORS跨域配置类
 * 用于Spring Security的CORS配置
 */
@Slf4j
@Configuration
public class CorsConfig {
    
    @Value("${app.cors.allowed-origins:http://localhost:3000}")
    private String allowedOrigins;
    
    @Value("${app.cors.allowed-methods:GET,POST,PUT,DELETE,OPTIONS,PATCH}")
    private String allowedMethods;
    
    @Value("${app.cors.allowed-headers:*}")
    private String allowedHeaders;
    
    @Value("${app.cors.allow-credentials:true}")
    private boolean allowCredentials;
    
    @Value("${app.cors.max-age:3600}")
    private long maxAge;
    
    @PostConstruct
    public void logCorsConfig() {
        log.info("========================================");
        log.info("CORS配置已加载:");
        log.info("  允许的源: {}", allowedOrigins);
        log.info("  允许的方法: {}", allowedMethods);
        log.info("  允许的请求头: {}", allowedHeaders);
        log.info("  允许携带凭证: {}", allowCredentials);
        log.info("  预检缓存时间: {}秒", maxAge);
        log.info("========================================");
    }
    
    /**
     * 配置CORS，供Spring Security使用
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许的源
        List<String> origins = Arrays.asList(allowedOrigins.split(","));
        configuration.setAllowedOrigins(origins);
        
        // 也支持模式匹配（推荐使用）
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        
        // 允许的HTTP方法
        List<String> methods = Arrays.asList(allowedMethods.split(","));
        configuration.setAllowedMethods(methods);
        
        // 允许的请求头
        if ("*".equals(allowedHeaders)) {
            configuration.addAllowedHeader("*");
        } else {
            List<String> headers = Arrays.asList(allowedHeaders.split(","));
            configuration.setAllowedHeaders(headers);
        }
        
        // 允许携带认证信息
        configuration.setAllowCredentials(allowCredentials);
        
        // 暴露的响应头（前端可以访问的响应头）
        configuration.setExposedHeaders(Arrays.asList(
            "Authorization",
            "x-auth-token",
            "X-Auth-Token",
            "X-Total-Count",
            "X-Session-Id",
            "Content-Disposition"
        ));
        
        // 预检请求缓存时间
        configuration.setMaxAge(maxAge);
        
        // 注册CORS配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }
}

